export default {
    /**
     * 倒计时
     * @param {String} endDate [结束时间]
     * @param {Function} once [倒计时回调]
     * @param {Function} end [倒计时结束回调]
     * @param {String} opt.sysDate [系统时间]
     * @param {Number, Function} opt.interval [倒计时间隔]
     */
    countdown(endDate, once, end, opt) {
    	opt = Object.assign({
    		showDay: true,
    		showHour: true,
    		interval: 1000
    	}, opt || {});
    
    	var timer,
    		interval = s => {
    			return typeof opt.interval == 'function' ? opt.interval(s) : opt.interval;
    		};
    
    	endDate = typeof endDate == 'object' ? endDate : [endDate];
    	endDate.forEach((item, i) => {
    		endDate[i] = opt.sysDate ? praseTime(item) - praseTime(opt.sysDate) + new Date().getTime() : praseTime(item);
    	});
    	
    	function praseTime(str) {
    		if (typeof str == 'number') {
    			if (`${str}`.length == 10) {
    				return str * 1000;
    			} else {
    				return str;
    			}
    		}
    		return (new Date(Date.parse(str.replace(/-/g,"/")))).getTime();
    	};
    
    	function getDouble(num) {
    		if (num < 10) return '0'+num;
    		return num;
    	};
    
    	!function loop() {
    		var goon = false,
    			s = 0;
    		endDate.forEach((item, i) => {
    			if (item == 'end') return;
    			s = item - new Date().getTime();
    			
    			var t = s < 0 ? 0 : s;
    			var day = 0,
    				hour = 0;
    			if (opt.showDay) {
    				day = parseInt((t/86400000).toFixed(10));
    				t -= day*86400000;
    			}
    			if (opt.showHour) {
    				hour = getDouble(parseInt((t/3600000).toFixed(10)));
    				t -= hour*3600000;
    			}
    			var min = getDouble(parseInt((t/60000).toFixed(10)));
    			t -= min*60000;
    			var sec = getDouble(parseInt((t/1000).toFixed(10)));
    			t -= sec*1000;
    			var ms = parseInt(t/100);
    	
    			var data = {
    				day: day,
    				hour: hour,
    				min: min,
    				sec: sec,
    				ms: ms,
    				count: s
    			};
    	
    			once && once(data, i);
    			if (s <= interval(s)) {
    				endDate[i] = 'end';
    				end && end(data, i);
    			} else {
    				goon = true;
    			}
    		});
    
    		// if (goon) timer = setTimeout(loop, interval(s));
    	}();
    
    	return {
    		abort() {
    			clearTimeout(timer);
    		}
    	}
    }
}